import getRandom from "./getRandom";

class Spark {
    constructor(ctx, canvas, x, y, config) {
        this.ctx = ctx;
        this.pos = [x, y];
        this.v = [
            config.meanSparkVelocity[0] * (Math.random() - 0.5),
            -1 * config.meanSparkVelocity[1] * Math.random()
        ];
        this.life = this.lifeOrig = Math.floor(config.meanSparkLife * Math.random());
        this.config = config;
        this.lg = true;

        this.img = document.getElementById(`ash${getRandom(1, 3)}`)
    }

    move () {
        for (let i = 0; i < 2; i++) {
            this.pos[i] += this.v[i] * (1 - this.life / this.lifeOrig);
        }
    }

    getAlpha () {
        return Math.sqrt(this.life / this.lifeOrig) + ((Math.random() - 0.5) / this.config.sparkBlink)
    }

    update () {
        this.move();
        if (!(this.life--)){ return true; }
        this.ctx.beginPath();
        this.ctx.globalAlpha = this.getAlpha();
        this.ctx.drawImage(this.img,this.pos[0],this.pos[1]);
    }
}

export default Spark;